import React from "react";
import type { DescriptionsProps } from "antd";
import { useNavigate } from "react-router-dom";
import type { APP } from "@/pages/hosting/typings";
import { DownloadOutlined } from "@ant-design/icons";
import Editor, { loader } from "@monaco-editor/react";
loader.config({ paths: { vs: "/monaco-editor/vs" } });
import { postDownloadFile } from "@/services/hosting/api";
import { Badge, Descriptions, Button, Space, message, Tooltip } from "antd";
interface Props extends Partial<APP> {}

const Info: React.FC<Props> = (app: Props) => {
    // 获取路由参数
    const params = new URLSearchParams(location.search);
    const stype = params.get("type");
    const navigate = useNavigate();
    const nodeId = new URLSearchParams(window.location.search).get("nodeId") as string;
    const getStatusBadge = (status?: string) => {
        switch (status?.toLowerCase()) {
            case "running":
                return { status: "processing", text: "运行中" };
            case "dead":
                return { status: "default", text: "已停止" };
            case "error":
                return { status: "error", text: "异常" };
            case "mapping":
                return { status: "processing", text: "已启用" };
            case "unmapped":
                return { status: "default", text: "未启用" };
            default:
                return { status: "default", text: "未知状态" };
        }
    };

    const downloadFile = async () => {
        const success = await postDownloadFile(
            app.app_id as string,
            stype as string,
            nodeId,
            navigate,
        );
        if (success) {
            message.success({ content: "下载中...", key: "download" });
        } else {
            message.error({ content: "下载失败", key: "download" });
        }
    };

    class Translate {
        node(node: string) {
            if (node === "0") {
                return "本机";
            }
            return node;
        }
        keepalive(keepalive: string) {
            return "--";
        }
        alias(alias: string) {
            if (alias) {
                return alias;
            }
            return "未命名应用";
        }
        version(version: string) {
            if (version) {
                return version;
            }
            return "--";
        }
        inpara(inpara: string) {
            if (inpara) {
                return inpara;
            }
            return "--";
        }
        nginxConfig(nginxConfig: string) {
            if (nginxConfig) {
                return nginxConfig;
            }
            return "--";
        }
        notes(notes: string) {
            if (notes) {
                return notes;
            }
            return "--";
        }
        status(status: string) {
            if (status) {
                return status;
            }
            return "--";
        }
        deploy_time(deploy_time: string) {
            if (deploy_time) {
                return deploy_time;
            }
            return "--";
        }
        create_time(create_time: string) {
            if (create_time) {
                return create_time;
            }
            return "--";
        }
        update_time(update_time: string) {
            if (update_time) {
                return update_time;
            }
            return "--";
        }
        file_name(file_name: string) {
            if (file_name) {
                return file_name;
            }
            return "--";
        }
    }

    // 构建基础 items 数组（不包含动态配置项）
    const baseItems: DescriptionsProps["items"] = [
        {
            key: "1",
            label: "应用名称",
            children: new Translate().alias(app.alias as string),
        },
        {
            key: "2",
            label: "文件名",
            span: 2,
            children: (
                <Space>
                    <div>
                        {new Translate().file_name(app.file_name as string)}
                    </div>
                    <Tooltip title="下载">
                        <Button
                            icon={<DownloadOutlined />}
                            size={"small"}
                            type={"text"}
                            style={{ color: "bule" }}
                            onClick={downloadFile}
                        ></Button>
                    </Tooltip>
                </Space>
            ),
        },
        {
            key: "5",
            label: "状态",
            children: (
                <Badge
                    status={
                        getStatusBadge(
                            new Translate().status(app?.status as string),
                        ).status as
                            | "processing"
                            | "default"
                            | "error"
                            | "success"
                            | "warning"
                            | undefined
                    }
                    text={
                        getStatusBadge(
                            new Translate().status(app?.status as string),
                        ).text
                    }
                />
            ),
        },
        {
            key: "3",
            label: "所属节点",
            children: new Translate().node(app.node as string),
        },
        {
            key: "7",
            label: "保活状态",
            children: new Translate().keepalive(app.keepalive as string),
        },
        {
            key: "4",
            label: "发布时间",
            children: new Translate().deploy_time(app.deploy_time as string),
        },
        {
            key: "6",
            label: "创建时间",
            children: new Translate().create_time(app.create_time as string),
        },
        {
            key: "10",
            label: "版本号",
            span: 2,
            children: new Translate().version(app.version as string),
        },
        {
            key: "9",
            label: "备注",
            span: 3,
            children: new Translate().notes(app.notes as string),
        },
    ];

    // 根据 stype 动态添加配置项到最底部
    const getDynamicItems = (): DescriptionsProps["items"] => {
        const items = [...baseItems];

        if (stype === "Java") {
            // 插入 JVM 参数到备注之前
            const notesIndex = items.findIndex((item) => item.key === "9");
            items.splice(notesIndex, 0, {
                key: "8",
                label: "JVM参数",
                span: 3,
                children: new Translate().inpara(app.inpara as string),
            });
        } else if (stype === "Static") {
            // 插入 Nginx 配置到最底部，单独一行p
            items.push({
                key: "11",
                label: "Nginx配置",
                span: 3, // 设置为3列宽度，占满整行
                children: (
                    <div
                        style={{
                            flex: 1,
                            overflow: "hidden",
                            borderRadius: "10px",
                            border: "1px solid #f0f0f0",
                        }}
                    >
                        <Editor
                            height={"35vh"}
                            language="nginx"
                            theme="light"
                            value={app.nginx_conf}
                            options={{
                                readOnly: true,
                                fontSize: 14,
                                minimap: { enabled: false },
                                scrollBeyondLastLine: false,
                                lineNumbers: "on",
                                folding: true,
                                lineDecorationsWidth: 10,
                                lineNumbersMinChars: 3,
                                wordWrap: "on",
                                automaticLayout: true,
                            }}
                        />
                    </div>
                ),
            });
        }

        return items;
    };

    const items: DescriptionsProps["items"] = getDynamicItems();

    return (
        <div
            style={{
                margin: "20px 0 0 0",
            }}
        >
            <Descriptions bordered items={items} />
        </div>
    );
};

export default Info;
